require 'ostruct'

class Material < ActiveRecord::Base
  has_many :materials_wish_lists
  has_many :wish_lists, :through => :materials_wish_lists

  has_many :materials_publishers
  has_many :publishers, :through => :materials_publishers

  has_many :authors_materials
  has_many :authors, :through => :authors_materials

  belongs_to :currency
  belongs_to :material_type
  belongs_to :thematic
  belongs_to :catalog_state

  has_many :serials
  has_and_belongs_to_many :descriptors


  ORDER_TYPES = [ 'catalog_order_types.relevance', 'catalog_order_types.title', 'catalog_order_types.author', 'catalog_order_types.publisher', 'catalog_order_types.country', 'catalog_order_types.year']

  ######################################################### LO NUEVO DEL MOTOR DE BUSQUEDAS #################################################################3

  # metodo donde se definen todos los indexes utilizados por sphinx
  define_index do
    # sobre atributos de materiales
    indexes [:title, :sub_title], :as => :title, :sortable => true                                           #free_search, advance_search
    indexes :sub_title                                                          #free_search, advance_search
    indexes :isbn                                                               #free_search, advance_search
    indexes :issn
    indexes :collection                                                         #free_search
    indexes :edition_year, :as => :edition_year, :sortable => true, :facet => true  #advance_search, filters_count
    indexes :edition_number, :as => :edition_number, :sortable => true, :facet => true  #filters_search, filters_count

    has :material_type_id, :as => :material_type_id

    #sobre tematicas
    has :thematic_id, :as => :thematic_id, :facet => true                       #filters_search, filters_count

    # sobre authores
    indexes authors.full_name, :as => :author_full_name, :sortable => true      #free_search, advance_search
    has authors.id, :as => :author_id, :facet => true                           #filters_search, filters_count

    #sobre editores
    indexes publishers.name, :as => :publisher_name, :sortable => true         #free_search, advance_search
    has publishers.id, :as => :publisher_id, :facet => true                     #filters_search, filters_count

    #sobre paises de editores
    indexes publishers.city.state.country.name, :as => :publisher_country_name, :sortable => true
    has publishers.city.state.country.id, :as => :publisher_country_id, :facet => true  #filters_search, advance_search, filters_count

    #descriptores
    indexes descriptors.description, :as => :descriptor_desc
    has descriptors.id, :as => :descriptor_id

    # se definen los pesos de cada indice
    set_property :field_weights => {
      :title => 3,
      :sub_title => 3,
      :author_full_name => 2,
      :publisher_name => 2,
      :isbn => 1,
      :collection => 1,
      :edition_year => 1,
      :publisher_country_name => 1,
      :descriptor_desc => 1
    }
  end

  #realiza la busqueda de los materiales a través de sphinx
  def self.search_engine_from_catalog current_user, page, record_parms_search, calculate_facet
   
    search_engine_text,
    search_engine_conditions,
    search_engine_with_options,
    search_engine_without_options,
    search_engine_match_mode,
    search_engine_star,
    search_engine_order,
    search_engine_order_mode    = search_engine_configuration current_user, record_parms_search

    items_per_page = count_record_per_page :catalogs

    start = Time.now
    materials = Material.search search_engine_text,
                                :conditions => search_engine_conditions,
                                :with => search_engine_with_options,
                                :without => search_engine_without_options,
                                :match_mode => search_engine_match_mode,
                                :star => search_engine_star,
                                :sort_mode => search_engine_order_mode,
                                :order => search_engine_order,
                                :page => page,
                                :per_page => items_per_page

    puts "search #{Time.now - start} segundos"
    puts "ERROR: #{materials.results[:error]}"

    if calculate_facet
      start = Time.now
      materials_facet = Material.facets search_engine_text,
                                        :conditions => search_engine_conditions,
                                        :with => search_engine_with_options,
                                        :without => search_engine_without_options,
                                        :match_mode => search_engine_match_mode,
                                        :star => search_engine_star,
                                        :group_clause   => "@count desc"
      puts "facets #{Time.now - start} segundos"
    end

    record_search_result = OpenStruct.new
    record_search_result.materials = materials
    record_search_result.filters_trees = materials_facet
    return record_search_result
  end

  #realiza la busqueda de los materiales a través de sphinx
  def self.search_engine record_parms_search

    record_parms_search = OpenStruct.new if record_parms_search.nil?
    
    search_engine_text,
    search_engine_conditions,
    search_engine_with_options,
    search_engine_without_options,
    search_engine_match_mode,
    search_engine_star,
    search_engine_order,
    search_engine_order_mode    = search_engine_configuration "current_user", record_parms_search

    items_per_page = count_record_per_page :materials
#    page = if record_parms_search.nil? then 1 else record_parms_search.page end
    
    start = Time.now
    materials = Material.search search_engine_text,
                                :conditions => search_engine_conditions,
                                :with => search_engine_with_options,
                                :without => search_engine_without_options,
                                :match_mode => search_engine_match_mode,
                                :star => search_engine_star,
                                :sort_mode => search_engine_order_mode,
                                :order => search_engine_order,
                                :page => record_parms_search.page,
                                :per_page => items_per_page

    puts "search #{Time.now - start} segundos"
    puts "ERROR: #{materials.results[:error]}"

    return materials
  end

  private

  def self.string_search_parse text
    return text.gsub(" ", "|")
    #text.gsub(/( |(".*?"))/, "\\2|")
  end

  # se determinan todas las condiciones y restricciones para la busqueda de materiales, segun los parametros recibidos
  def self.search_engine_configuration current_user, record_parms_search
    search_engine_text = nil
    search_engine_conditions = {}
    search_engine_with_options = {}
    search_engine_without_options = {}
    search_engine_match_mode = :any     #por defecto se busca con un OR (se asume busqueda de texto libre)
    search_engine_star = false

    #se excluye libros de cuba si no existe sesion
    country_id_cuba = Setting.country_id_cuba
    if current_user.nil? and !country_id_cuba.nil?
      search_engine_without_options[:publisher_country_id] = country_id_cuba
    end

    if !record_parms_search.nil?
      #se carga el texto libre a buscar
      if !record_parms_search.free_text_search.nil? && record_parms_search.free_text_search.size > 0
        search_engine_text = record_parms_search.free_text_search
      end

      #se cargan las restricciones sobre los atributos del motor
      search_engine_with_options[:thematic_id] = record_parms_search.thematic_id unless record_parms_search.thematic_id.nil?
      search_engine_with_options[:author_id] = record_parms_search.author_id unless record_parms_search.author_id.nil?
      search_engine_with_options[:publisher_id] = record_parms_search.publisher_id unless record_parms_search.publisher_id.nil?
      search_engine_with_options[:publisher_country_id] = record_parms_search.publisher_country_id unless record_parms_search.publisher_country_id.nil?
      search_engine_with_options[:material_type_id] = record_parms_search.material_type_id unless record_parms_search.material_type_id.nil?

      #search_engine_with_options[:edition_year] = record_parms_search.year unless record_parms_search.year.nil?
      #search_engine_with_options[:edition_number] = record_parms_search.edition unless record_parms_search.edition.nil?

      #se cargan las restricciones sobre los indices del motor
      #se tiene que procesar el string de cada campo para agregarle el or entre las palabras

      search_engine_conditions[:title] = string_search_parse record_parms_search.title unless record_parms_search.title.nil?
      search_engine_conditions[:author_full_name] = string_search_parse record_parms_search.author_full_name unless record_parms_search.author_full_name.nil?
      search_engine_conditions[:publisher_name] = string_search_parse record_parms_search.publisher_name unless record_parms_search.publisher_name.nil?
      search_engine_conditions[:publisher_country_name] = string_search_parse record_parms_search.publisher_country_name unless record_parms_search.publisher_country_name.nil?
      search_engine_conditions[:isbn] = "\"#{record_parms_search.isbn}\"" unless record_parms_search.isbn.nil?  #porque el isbn tiene '-' y eso en la busqueda extendida funciona como un or
      search_engine_conditions[:issn] = "\"#{record_parms_search.issn}\"" unless record_parms_search.issn.nil?  #porque el issn tiene '-' y eso en la busqueda extendida funciona como un or
      search_engine_conditions[:edition_year] = string_search_parse record_parms_search.edition_year unless record_parms_search.edition_year.nil?
      search_engine_conditions[:edition_number] = string_search_parse record_parms_search.edition_number unless record_parms_search.edition_number.nil?

      descriptor_desc = ""
      if !record_parms_search.descriptor1.nil?
        descriptor_desc << record_parms_search.descriptor1
      end
      if !record_parms_search.descriptor2.nil?
        connector = if record_parms_search.descriptor_connector1.downcase! == 'and' then "&" else "|" end
        descriptor_desc << " #{connector} #{record_parms_search.descriptor2}"
      end
      if !record_parms_search.descriptor3.nil?
        connector = if record_parms_search.descriptor_connector2.downcase! == 'and' then "&" else "|" end
        descriptor_desc << " #{connector} #{record_parms_search.descriptor3}"
      end
      if descriptor_desc.size > 0
        search_engine_conditions[:descriptor_desc] = descriptor_desc
      end
    end

    if search_engine_conditions.size > 0
      #como hay que buscar en algunos de los indices tenemos que cambiar el modo de busqueda
      search_engine_match_mode = :extended
    end

    #se define el orden
    if !record_parms_search.nil?

      case record_parms_search.catalog_order_type
      when 'catalog_order_types.relevance'
        search_engine_order = "@relevance DESC, title ASC"
        search_engine_order_mode = :extended
      when 'catalog_order_types.title'
        search_engine_order = "title ASC"
        search_engine_order_mode = :extended
      when 'catalog_order_types.author'
        search_engine_order = "author_full_name ASC, title ASC"
        search_engine_order_mode = :extended
      when 'catalog_order_types.publisher'
        search_engine_order = "publisher_name ASC, title ASC"
        search_engine_order_mode = :extended
      when 'catalog_order_types.country'
        search_engine_order = "publisher_country_name ASC, title ASC"
        search_engine_order_mode = :extended
      when 'catalog_order_types.year'
        search_engine_order = "edition_year DESC, title ASC"
        search_engine_order_mode = :extended
      else
        search_engine_order = "title ASC"
        search_engine_order_mode = :extended
      end

    else
        search_engine_order = "@relevance DESC, title ASC"
        search_engine_order_mode = :extended
    end

    puts "search_engine_text: #{search_engine_text} \n
          search_engine_conditions: #{search_engine_conditions} \n
          search_engine_with_options: #{search_engine_with_options} \n
          search_engine_without_options: #{search_engine_without_options}\n
          search_engine_match_mode: #{search_engine_match_mode} \n
          search_engine_star: #{search_engine_star} \n
          search_engine_order: #{search_engine_order} \n
          search_engine_order_mode: #{search_engine_order_mode} \n"

    return search_engine_text, search_engine_conditions, search_engine_with_options, search_engine_without_options, search_engine_match_mode, search_engine_star, search_engine_order, search_engine_order_mode
  end

  ######################################################### LO NUEVO DEL MOTOR DE BUSQUEDAS #################################################################


################################ RESPALDO DE LAS CONSULTAS DEL CATALOGO ##################################

=begin
  def self.find_material current_user, page, record
    query = "select distinct materials.* "
    query += " , authors.full_name" if record.catalog_order_type == 'catalog_order_types.author'
    query += " , publishers.name" if record.catalog_order_type == 'catalog_order_types.publisher'
    query += " , countries.name" if record.catalog_order_type == 'catalog_order_types.country'

    query += " from materials "
    parameter = []

    query += create_join_condition current_user, record
    query += " where 2 = 2 "
    query += create_where_query_condition current_user, record
    parameter += create_where_parameter_condition record

    query += "order by title " if record.catalog_order_type.nil? || record.catalog_order_type == 'catalog_order_types.title'
    query += "order by authors.full_name" if record.catalog_order_type == 'catalog_order_types.author'
    query += "order by publishers.name" if record.catalog_order_type == 'catalog_order_types.publisher'
    query += "order by countries.name" if record.catalog_order_type == 'catalog_order_types.country'
    query += "order by edition_year" if record.catalog_order_type == 'catalog_order_types.year'


    items_per_page = count_record_per_page :catalogs
    Material.paginate_by_sql [query] + parameter, :page => page, :per_page => items_per_page, :include => [:authors, {:publishers => [ {:city => [:state => :country]}]}, :thematic, :descriptors]

  end

  def self.find_for_thematics current_user, page, record
    #Armo la consulta para armar la lista de thematics
    if I18n.locale == 'es'
      query = "select thematics.id as thematic_id, thematics.name_web_es as name, count(distinct materials.*) as cant"
    else
      query = "select thematics.id as thematic_id, thematics.name_web_en as name, count(distinct materials.*) as cant"
    end

    query += " from materials inner join thematics on materials.thematic_id = thematics.id "
    parameter = []

    query += create_join_condition current_user, record

    query += " where 2 = 2 "
    query += create_where_query_condition current_user, record
    parameter += create_where_parameter_condition record

    #Finalmente agrego el group by
    if I18n.locale == 'es'
      query += "group by  thematics.id, thematics.name_web_es "
      query += "order by cant desc, thematics.name_web_es "
    else
      query += "group by  thematics.id, thematics.name_web_en "
      query += "order by cant desc, thematics.name_web_en "
    end

    items_per_page = count_record_per_page :thematics_filter
    Material.paginate_by_sql [query] + parameter, :page => page, :per_page => items_per_page
  end

  def self.find_for_authors current_user, page, record
        #Armo la consulta para armar la lista de autores
    query = "select authors.id as author_id, authors.full_name as full_name, count(distinct materials.*) as cant
              from materials "
    parameter = []

    query += create_join_condition current_user, record
    query += " where 2 = 2 "
    query += create_where_query_condition current_user, record
    parameter += create_where_parameter_condition record

    #Finalmente agrego el group by
    query += "group by  authors.id, authors.full_name "
    query += "order by cant desc, authors.full_name "

    items_per_page = count_record_per_page :authors_filter
    Material.paginate_by_sql [query] + parameter, :page => page, :per_page => items_per_page
  end

  def self.find_for_countries current_user, page, record
    query = "select countries.id as city_id, countries.name as name, count(distinct materials.*) as cant
              from materials "
    parameter = []

    query += create_join_condition current_user, record
    query += " where 2 = 2 "
    query += create_where_query_condition current_user, record
    parameter += create_where_parameter_condition record

    #Finalmente agrego el group by
    query += "group by countries.id, countries.name "
    query += "order by cant desc, countries.name "

    items_per_page = count_record_per_page :countries_filter
    Material.paginate_by_sql [query] + parameter, :page => page, :per_page => items_per_page
  end

  def self.find_for_editors current_user, page, record
    query = "select publishers.id as publisher_id, publishers.name as name, count(distinct materials.*) as cant
              from materials "
    parameter = []

    query += create_join_condition current_user, record
    query += " where 2 = 2 "
    query += create_where_query_condition current_user, record
    parameter += create_where_parameter_condition record

    #Finalmente agrego el group by
    query += "group by publishers.id, publishers.name "
    query += "order by cant desc, publishers.name "

    items_per_page = count_record_per_page :editors_filter
    Material.paginate_by_sql [query] + parameter, :page => page, :per_page => items_per_page
  end

  def self.find_for_years current_user, page, record
    query = "select materials.edition_year as edition_year, count(distinct materials.*) as cant
              from materials "
    parameter = []

    query += create_join_condition current_user, record
    query += " where 2 = 2 "
    query += create_where_query_condition current_user, record
    parameter += create_where_parameter_condition record

    #Finalmente agrego el group by
    query += "group by materials.edition_year "
    query += "order by cant desc, materials.edition_year "

    items_per_page = count_record_per_page :years_filter
    Material.paginate_by_sql [query] + parameter, :page => page, :per_page => items_per_page
  end

  def self.find_for_editions current_user, page, record
    query = "select materials.edition_number as edition_number, count(distinct materials.*) as cant
              from materials "
    parameter = []

    query += create_join_condition current_user, record
    query += " where 2 = 2 "
    query += create_where_query_condition current_user, record
    parameter += create_where_parameter_condition record

    #Finalmente agrego el group by
    query += "group by materials.edition_number "
    query += "order by cant desc, materials.edition_number "
    items_per_page = count_record_per_page :editions_filter
    Material.paginate_by_sql [query] + parameter, :page => page, :per_page => items_per_page
  end

  def self.create_where_query_condition current_user, record
    query = ""

    #Excluyo los libros que no se deben mostrar y los que tienen precio 0
    query += "and materials.show_web and (materials.price is not null and materials.price > 0)"

    #Excluyo libros de cuba
    country_id_cuba = Setting.country_id_cuba
    query += "and countries.id != #{country_id_cuba} " if current_user.nil? and !country_id_cuba.nil?

    #condiciones de los filtros del catalogo
    query += "and materials.thematic_id = ? "  unless record.thematic_id.nil?
    query += "and authors.id = ? " unless record.author_id.nil?
    query += "and countries.id = ? " unless record.country_id.nil?
    query += "and publishers.id = ? " unless record.publisher_id.nil?
    query += "and materials.edition_year = ? " unless record.year.nil?
    query += "and upper(materials.edition_number) = upper(?) " unless record.edition.nil?

    # NOTA: nunca van a a venir una busqueda avanzada junto a una busqueda de texto libre
    #       por lo tanto podemos reutilizar los joins
    #       las condiciones cambian porque en la primera es con and y la segunda con or

    if !record.free_text_search.nil? && record.free_text_search != ""
      #condiciones de la busqueda de texto libre
      query += "and("
      query += "( upper(materials.title) like upper(?) or upper(materials.sub_title) like upper(?) ) "
      query += "or upper(authors.full_name) like upper(?) "
      query += "or upper(publishers.name) like upper(?) "
      query += "or upper(materials.collection) like upper(?) "
      query += "or upper(materials.isbn) like upper(?) "
      if @free_text_search_descriptor_id != -1
        query += "or descriptors_materials1.descriptor_id = ? "
      end
      query += ") "

    else
      #condiciones de la busqueda avanzada (si controla una a una a ver si hay algo cargado)
      query += "and ( upper(materials.title) like upper(?) or upper(materials.sub_title) like upper(?)) " unless record.advance_search_title.nil? || record.advance_search_title == ""
      query += "and upper(authors.full_name) like upper(?) "        unless record.advance_search_author.nil? || record.advance_search_author == ""
      query += "and upper(publishers.name) like upper(?) "          unless record.advance_search_publisher.nil? || record.advance_search_publisher == ""
      query += "and upper(countries.name) like upper(?) "           unless record.advance_search_country.nil? || record.advance_search_country == ""
      query += "and upper(materials.edition_year) like upper(?) "   unless record.advance_search_year_search.nil? || record.advance_search_year_search == ""
      query += "and upper(materials.isbn) like upper(?) "           unless record.advance_search_isbn.nil? || record.advance_search_isbn == ""

      query += "and ( "                                             if !record.advance_search_descriptor1.nil? || !record.advance_search_descriptor2.nil? || !record.advance_search_descriptor3.nil?
      query += " descriptors_materials1.descriptor_id = ? "         if !record.advance_search_descriptor1.nil?
      query += record.advance_search_connector1                     if !record.advance_search_descriptor1.nil? && !record.advance_search_descriptor2.nil?
      query += " descriptors_materials2.descriptor_id = ? "         if !record.advance_search_descriptor2.nil?
      query += record.advance_search_connector2                     if !record.advance_search_descriptor3.nil? && (!record.advance_search_descriptor1.nil? || !record.advance_search_descriptor2.nil?)
      query += " descriptors_materials3.descriptor_id = ? "         if !record.advance_search_descriptor3.nil?
      query += ") "                                                 if !record.advance_search_descriptor1.nil? || !record.advance_search_descriptor2.nil? || !record.advance_search_descriptor3.nil?
    end


    puts "------------------ query -----------------"
    puts "#{query}"
    return query
  end

  def self.create_where_parameter_condition record

    parameter = []

    #parametros de los filtros del catalogo
    parameter += [record.thematic_id]  unless record.thematic_id.nil?
    parameter += [record.author_id] unless record.author_id.nil?
    parameter += [record.country_id] unless record.country_id.nil?
    parameter += [record.publisher_id] unless record.publisher_id.nil?
    parameter += [record.year] unless record.year.nil?
    parameter += [record.edition] unless record.edition.nil?

    #parametros de la busqueda avanzada
    descriptor1_id, descriptor2_id, descriptor3_id = get_descriptors_ids(record.advance_search_descriptor1, record.advance_search_descriptor2, record.advance_search_descriptor3)
    parameter += ['%' + record.advance_search_title.upcase + '%'] unless record.advance_search_title.nil? || record.advance_search_title == ""
    parameter += ['%' + record.advance_search_title.upcase + '%'] unless record.advance_search_title.nil? || record.advance_search_title == ""
    parameter += ['%' + record.advance_search_author.upcase + '%'] unless record.advance_search_author.nil? || record.advance_search_author == ""
    parameter += ['%' + record.advance_search_publisher.upcase + '%'] unless record.advance_search_publisher.nil? || record.advance_search_publisher == ""
    parameter += ['%' + record.advance_search_country.upcase + '%'] unless record.advance_search_country.nil? || record.advance_search_country == ""
    parameter += ['%' + record.advance_search_year_search.upcase + '%'] unless record.advance_search_year_search.nil? || record.advance_search_year_search == ""
    parameter += ['%' + record.advance_search_isbn.upcase + '%'] unless record.advance_search_isbn.nil? || record.advance_search_isbn == ""
    parameter += [descriptor1_id] unless record.advance_search_descriptor1.nil?
    parameter += [descriptor2_id] unless record.advance_search_descriptor2.nil?
    parameter += [descriptor3_id] unless record.advance_search_descriptor3.nil?

    #parametros de la busqueda de texto libre
    if !record.free_text_search.nil? && record.free_text_search != ""
      parameter += ['%' + record.free_text_search.upcase + '%']
      parameter += ['%' + record.free_text_search.upcase + '%']
      parameter += ['%' + record.free_text_search.upcase + '%']
      parameter += ['%' + record.free_text_search.upcase + '%']
      parameter += ['%' + record.free_text_search.upcase + '%']
      parameter += ['%' + record.free_text_search.upcase + '%']
      if @free_text_search_descriptor_id != -1
        parameter += [@free_text_search_descriptor_id]
      end
    end

    puts "------------------ parametros -----------------"
    puts "#{parameter}"
    return parameter
  end

  def self.get_descriptors_ids(descriptor1, descriptor2, descriptor3)
    if !descriptor1.nil?
      d1 = Descriptor.find(:first, :conditions => ["upper(description) like upper(?)", "#{descriptor1}"])
      descriptor1_id = d1.id if !d1.nil?
      descriptor1_id = -1 if d1.nil?
    end

    if !descriptor2.nil?
      d2 = Descriptor.find(:first, :conditions => ["upper(description) like upper(?)", "#{descriptor2}"])
      descriptor2_id = d2.id if !d2.nil?
      descriptor2_id = -1 if d2.nil?
    end

    if !descriptor3.nil?
      d3 = Descriptor.find(:first, :conditions => ["upper(description) like upper(?)", "#{descriptor3}"])
      descriptor3_id = d3.id if !d3.nil?
      descriptor3_id = -1 if d3.nil?
    end

    return descriptor1_id, descriptor2_id, descriptor3_id
  end

  def self.create_join_condition current_user, record
    query = ""
    query += " inner join authors_materials on materials.id = authors_materials.material_id " unless record.author_id.nil? && record.author_search == ""
    query += " inner join authors on authors_materials.author_id = authors.id " unless record.author_id.nil? && record.author_search == ""

    #Esto se comenta, porque para excluir los libros de cuba, si o si tienen que ir estas relaciones, por lo cual se saca las condiciones
#    query += " inner join materials_publishers on materials.id = materials_publishers.material_id " unless publisher.nil? && publisher_search == "" && country_search == "" && country.nil?
#    query += " inner join publishers on materials_publishers.publisher_id = publishers.id " unless publisher.nil? && publisher_search == "" && country_search == "" && country.nil?
#    query += " inner join cities on cities.id = publishers.city_id " unless country_search == "" && country.nil?
#    query += " inner join states on states.id = cities.state_id " unless country_search == "" && country.nil?
#    query += " inner join countries on countries.id = states.country_id " unless country_search == "" && country.nil?

    #Por lo tanto, van los join sin condiciones
    country_id_cuba = Setting.country_id_cuba
    query += " inner join materials_publishers on materials.id = materials_publishers.material_id "
    query += " inner join publishers on materials_publishers.publisher_id = publishers.id "
    query += " inner join cities on cities.id = publishers.city_id " if (current_user.nil? and !country_id_cuba.nil?) || !(record.advance_search_country == "" && record.country_id.nil?)
    query += " inner join states on states.id = cities.state_id " if (current_user.nil? and !country_id_cuba.nil?) || !(record.advance_search_country == "" && record.country_id.nil?)
    query += " inner join countries on countries.id = states.country_id " if (current_user.nil? and !country_id_cuba.nil?) || !(record.advance_search_country == "" && record.country_id.nil?)

    # joins para los descriptores de la busqueda avanzada y de texto libre
    @free_text_search_descriptor_id = -1
    if !record.free_text_search.nil? && record.free_text_search != ""
      puts "a ver si encuentro el descriptor"
      @free_text_search_descriptor_id, temp1, temp2 = get_descriptors_ids(record.free_text_search, nil, nil)
      puts "el id que encontre es: #{@free_text_search_descriptor_id}"
      if @free_text_search_descriptor_id != -1
        query += " inner join descriptors_materials descriptors_materials1 on materials.id = descriptors_materials1.material_id "
      end
    else
      query += " inner join descriptors_materials descriptors_materials1 on materials.id = descriptors_materials1.material_id " unless record.advance_search_descriptor1.nil?
      query += " inner join descriptors_materials descriptors_materials2 on materials.id = descriptors_materials2.material_id " unless record.advance_search_descriptor2.nil?
      query += " inner join descriptors_materials descriptors_materials3 on materials.id = descriptors_materials3.material_id " unless record.advance_search_descriptor3.nil?
    end

    return query
  end
=end

end